package oauth2.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import util.HttpClientUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
public class OAuth2Controller {

    @Value("${OAuth2.clientId}")
    private String clientId;

    @Value("${OAuth2.clientSecret}")
    private String clientSecret;

    @Value("${OAuth2.redirectURI}")
    private String redirectURI;

    @Value("${OAuth2.getTokenURI}")
    private String getTokenURI;

    @Value("${OAuth2.getUserInfoURI}")
    private String getUserInfoURI;

    @GetMapping("/callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = (String)request.getParameter("url");
        //获取授权码
        String code = request.getParameter("code");
        //获取token
        HashMap getTokenParams = new HashMap();
        getTokenParams.put("code", code);
        getTokenParams.put("client_id", clientId);
        getTokenParams.put("client_secret", clientSecret);
        getTokenParams.put("redirect_uri", redirectURI);
        getTokenParams.put("grant_type", "authorization_code");
        getTokenParams.put("response_type", "code");
        //发送post请求获取token
        JSONObject getTokenResults = HttpClientUtils.doPost(getTokenURI, null, JSON.toJSONString(getTokenParams));
        String accessToken = getTokenResults.getJSONObject("data").getString("access_token");
        //获取用户授权信息
        HashMap getUserInfopPrams = new HashMap();
        getUserInfopPrams.put("access_token", accessToken);
        getUserInfopPrams.put("client_id", clientId);
        //发送post请求获取用户信息
        JSONObject getUserInfoResults = HttpClientUtils.doPost(getUserInfoURI, null, JSON.toJSONString(getUserInfopPrams));
        //从用户信息中获取用户名
        String name = getUserInfoResults.getJSONObject("data").getString("name");
        request.getSession().setAttribute("user",name);
        response.sendRedirect(url != null ? url : "/demo/user");
    }
}
